package com.example.lxh.testinfo;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.LinkedList;

public class pulltofreshActivity extends AppCompatActivity {
    private LinkedList<String> mListItems;
    private PullToRefreshListView mPullRefreshlistView;
    private ArrayAdapter<String> mAdapter;
    private int mItemCount = 9;

    //  下拉刷新  下拉加载   的  ListView 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pulltofresh);
        mPullRefreshlistView = findViewById(R.id.pull_refresh_list);
        initData();
        mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mListItems);
        mPullRefreshlistView.setAdapter(mAdapter);

        mPullRefreshlistView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                new GetDataTask().execute();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                new GetDataTask().execute();
            }
        });
    }

    private class GetDataTask extends AsyncTask<Void, Void, String> {
        @Override
        protected String doInBackground(Void... voids) {
            try {
                Thread.sleep(2000);
            } catch (Exception e) {
            }
            return " Item : " + (mItemCount++);
        }

        @Override
        protected void onPostExecute(String s) {
            mListItems.add(s);
            mAdapter.notifyDataSetChanged();
            mPullRefreshlistView.onRefreshComplete();
        }
    }


    private void initData() {
        mListItems = new LinkedList<>();
        for (int i = 0; i < mItemCount; i++) {
            mListItems.add(" Item :" + i);
        }
    }
}
